<template>
	<view class="flex flex-direction align-center justify-center" style="width: 100%;height: 100vh;">
		<image @click="gotoMenu" style="width: 70vw" src="../../static/logo.png" mode="widthFix"></image>
		<text class="margin-top text-bold text-xl" @tap="showModal">{{loginText}}</text>
		<!-- <view class="flex flex-direction">
			<text v-for="(item,index) in authorize" :key="index">
				{{index}}:{{item}}
			</text>
		</view> -->
		<view class="cu-modal" :class="modalName=='Modal'?'show':''">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class="content">登录</view>
					
					<view class="action" @tap="hideModal">
						<text class="icon-close text-red"></text>
					</view>
				</view>
				<view class="padding">
					<view class="padding-sm flex align-center solid-bottom">
						<view class="flex-1">
							<text class="text-bold">用户名：</text>
						</view>
						<view class="flex-3 ">
							<input class="text-sm" style="width: 100%;" type="text" placeholder="请输入"
							v-model="loginUser.loginName"/>
						</view>
					</view>
					<view class="padding-sm flex solid-bottom">
						<view class="flex-1">
							<text class="text-bold">密码：</text>
						</view>
						<view class="flex-3">
							<input class="text-sm" style="width: 100%;" type="text" placeholder="请输入"
							v-model="loginUser.password"/>
						</view>
					</view>
					<view class="flex justify-center margin-top" style="width: 100%;">
						<view class="flex flex-direction">
							<button :loading="loginLoad" class="cu-btn bg-blue shadow padding-lr-xl" @tap="userSyslogin">授权登录</button>
							<text class="text-red margin-top-sm">{{OauthText}}</text>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script src="http://wechatfe.github.io/vconsole/lib/vconsole.min.js?v=3.2.0"></script>
<script>
	import Base64 from '../../common/base64.js';
	const base = new Base64();
	var jweixin = require('jweixin-module')
	export default {
		data() {
			return {
				OauthText:'',
				loginLoad: false,
				modalName:'',
				authorize:{},
				loginText:"登录中...",
				equipmentNo:'',
				userInfo: this.$helper.userInfo,
				loginUser: {
					loginName: "",
					password: "",
					// loginType: "NAME_PASSWORD"
				},
				CustomBar: this.CustomBar,
			}
		},
		onLoad(data) {
			var that = this;
			let equipmentNo = data.equipmentNo;
			let msgType = data.msgType;
			let isTimeout = data.isTimeout;
			// uni.showToast({
			// 	title: 'equipmentNo:'+equipmentNo,
			// 	icon: 'none',
			// 	duration: 3000
			// });
			if(equipmentNo){
				that.$helper.msgType = msgType;
				that.$helper.isTimeout = isTimeout;
				that.equipmentNo = equipmentNo;
			}
			// this.userlogin();
		},
		onShow() {
			this.userlogin();
			// this.authorizeUrl();
			// let authorize_url = uni.getStorageSync('authorize_url');
			// console.log("this.$helper.authorize_url:",this.$helper.authorize_url);
		},
		methods: {
			sysUserOauth2Login(data){
				var that = this;
				let loginName = data.loginName;
				console.log("base.encode(loginName):",base.encode(loginName));
				data.authorName = base.encode(loginName);
                data.scanGoal = '2';
                data.loginResultUrl = window.location.href.split('#')[0] + '#/pages/index/index';
				data.loginType = 'WECHAT_ENTERPRISE_WEB';
				data.oauthPassKey = that.authorize.oauthPassKey;
				that.OauthText = '授权中...';
				console.log("data:",data);
				that.$api.sysUserOauth2Login(data).then(res => {
					console.log("sysUserOauth2Login:", res);
					if (res.code == 0) {
						that.OauthText = '授权成功';
						that.getWechatEnterpriseSignature();
						that.hideModal();
					} else {
						that.OauthText = res.message;
					}
				}).catch(error => {
					uni.hideLoading();
					that.OauthText = '服务器异常:'+ JSON.stringify(error);
				})
			},
			userSyslogin() {
				var that = this;
				let data = that.loginUser;
				// data.loginName = base.encode(data.loginName);
				data.loginType = 'NAME_PASSWORD';
                data.tenantId = that.$helper.tenantId;
				that.loginLoad = true;
				that.OauthText = '登录中...';
				that.$api.userlogin(data).then(res => {
					that.loginLoad = false;
					console.log("userSyslogin:", res);
					if (res.code == 0) {
						that.userInfo = res.data.userVO;
						that.$helper.userInfo = res.data.userVO;
						that.$helper.token = res.data.authToken;
						that.sysUserOauth2Login(data);
					} else {
						that.OauthText = "登录失败："+res.message;
					}
				}).catch(error => {
					that.loginLoad = false;
					that.OauthText = "登录异常："+JSON.stringify(error);
				})
			},
			showModal(e) {
				if(this.authorize.oauthResultCode == 2){
					this.modalName = "Modal"
				}
			},
			hideModal(e) {
				this.modalName = null
			},
			gotoMenu(){
				uni.reLaunch({
					url: '../menu/menu'
				})
			},
			// getUrlParam(name) {
			// 	var that = this;
			//     let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
			// 	if(name == "oauthPassKey"){
			// 		reg = new RegExp("(^|?)" + name + "=([^&]*)(&|$)");
			// 	}
			//     let r = window.location.href.substr(1).match(reg);  //匹配目标参数
			// 	if(name == "oauthPassKey"){
			// 		uni.showModal({
			// 			title: '提示',
			// 			content: 'oauthPassKey:'+JSON.stringify(r),
			// 			success: res => {},
			// 			fail: () => {},
			// 			complete: () => {}
			// 		});
			// 	}
			//     if (r != null) return encodeURI(r[2]);
			//     return null; //返回参数值
			// },
			getUrlParam(name) {
			    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
			    let index = 2;
				if(name == 'oauthPassKey'){
					reg = new RegExp(name + "=([^&]*)(&|$)");
					index = 1;
				}
				let r = window.location.href.substr(1).match(reg);  //匹配目标参数
			    if (r != null) return encodeURI(r[index]);
			    return null; //返回参数值
			},
			authorizeUrl() {
				var that = this;
				var url = window.location.href.split('#')[0];
				let comitData = {
					"loginName": "",
					"loginResultUrl": url+"#/pages/menu/menu",
					"loginType": "WECHAT_ENTERPRISE_WEB",
					"scanGoal": "1"
				};
				that.$api.authorizeUrl(comitData).then(res =>{
						console.log("authorizeUrl:",res);
					if (res.code == 0) {
						window.location.href = res.data
					} else {
						uni.showToast({
							title: res.message,
							icon: 'none',
							duration: 3000
						});
					}
				}).catch(error =>{
					console.log(error);
				})
			},
			userlogin() {
				var that = this;
				let oauthResultCode = this.getUrlParam("oauthResultCode");
				let loginName = this.getUrlParam("loginName");
				let scanGoal = this.getUrlParam("scanGoal");
				let oauthPassKey = this.getUrlParam("oauthPassKey");
				let loginType = this.getUrlParam("loginType");
				this.authorize = {
					oauthResultCode,
					loginName,
					scanGoal,
					oauthPassKey,
					loginType
				}
				if(oauthResultCode != 1){
					let loginText = "授权失败,错误code:";
					if(oauthResultCode == 2){
						loginText = '账号未绑定,点击开始授权:';
						that.showModal();
					}
					that.loginText = loginText+oauthResultCode;
					return false;
				}
				let data = {
					loginName:  base.decode(loginName),
					password: oauthPassKey,
					tenantId: that.$helper.tenantId,
					loginType: loginType
				}
				
				//test
					// data.loginName = 'lys';
					// data.password = '123456';
					// data.loginType = 'NAME_PASSWORD';
				//
				that.$api.userlogin(data).then(res => {
					console.log("userlogin:", res);
					if (res.code == 0) {
						that.userInfo = res.data.userVO;
						that.$helper.userInfo = res.data.userVO;
						that.$helper.token = res.data.authToken;
						that.getWechatEnterpriseSignature();
					} else {
						uni.showToast({
							title: res.message,
							icon: 'none',
							duration: 3000
						});
					}
				}).catch(error => {
					console.log("error:", error);
				})
			},
			getWechatEnterpriseSignature() {
				var that = this;
				var url = window.location.href.split('#')[0];
				// var url = 'https://www.middol.com/colburn/service';
				that.$api.getWechatEnterpriseSignature({
					url: url
				}).then(res => {
					console.log("getWechatEnterpriseSignature:", res);
					if (res.code == 0) {
						that.loginText = '登录成功...跳转中'
						let resData = res.data;
						jweixin.config({
							beta: true,
							debug: false,
							signature: resData.signature,
							nonceStr: resData.nonceStr,
							appId: resData.appId,
							timestamp: resData.timestamp,
							jsApiList: ['scanQRCode','previewFile']
						})
						if(that.equipmentNo){
							that.$helper.equipmentNo = that.equipmentNo;
							uni.navigateTo({
								url: '../index/index'
							})
						}else{
							uni.navigateTo({
								url: '../menu/menu'
							})
						}
					}else{
						uni.showToast({
							title: res.message,
							icon: 'none',
							duration: 3000
						});
						that.loginText = '登录失败:'+JSON.stringify(res);
					}
				}).catch(error => {
					that.loginText = 'error:' + JSON.stringify(error);
					console.log("error:", error);
				})
			},
		},
	}
</script>

<style>
</style>
